<template>
  <div class="dashboard-container">
    <!-- 用户信息卡片 -->
    <el-card class="user-info-card">
      <template #header>
        <div class="card-header">
          <span>用户信息</span>
        </div>
      </template>
      <div class="user-info">
        <p><strong>用户名：</strong>{{ dashboardData.username }}</p>
        <p><strong>角色：</strong>{{ dashboardData.role }}</p>
        <p><strong>最后登录：</strong>{{ formatDate(dashboardData.lastLoginTime) }}</p>
      </div>
    </el-card>

    <!-- 数据概览卡片 -->
    <div class="overview-cards">
      <el-card class="overview-card">
        <template #header>
          <div class="card-header">
            <span>待发货订单</span>
          </div>
        </template>
        <div class="card-content">
          <h2>{{ dashboardData.pendingOrders }}</h2>
        </div>
      </el-card>

      <el-card class="overview-card">
        <template #header>
          <div class="card-header">
            <span>今日销售额</span>
          </div>
        </template>
        <div class="card-content">
          <h2>¥{{ dashboardData.todaySales.toFixed(2) }}</h2>
        </div>
      </el-card>

      <el-card class="overview-card">
        <template #header>
          <div class="card-header">
            <span>热销商品</span>
          </div>
        </template>
        <div class="card-content">
          <h3>{{ dashboardData.topProduct.name }}</h3>
          <p>销售额：¥{{ dashboardData.topProduct.sales.toFixed(2) }}</p>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>销售趋势</span>
          </div>
        </template>
        <div id="salesTrendChart" class="chart"></div>
      </el-card>

      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>分类销售统计</span>
          </div>
        </template>
        <div id="categorySalesChart" class="chart"></div>
      </el-card>

      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>分类销售占比</span>
          </div>
        </template>
        <div id="categoryPercentageChart" class="chart"></div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getDashboardData, getSalesTrend, getCategorySales, getSalesPercentage } from '@/api/dashboard'
import { formatDate } from '@/utils/format'
import type { 
  DashboardResponse, 
  SalesTrendResponse, 
  CategorySalesResponse, 
  CategoryPercentageResponse,
  ApiResponse 
} from '@/types/dashboard'

const hotProducts = ref([
  { name: '商品1', sales: 1234, price: 99.00 },
  { name: '商品2', sales: 1000, price: 199.00 },
  { name: '商品3', sales: 800, price: 299.00 },
  { name: '商品4', sales: 600, price: 399.00 },
  { name: '商品5', sales: 400, price: 499.00 }
])

// 仪表盘数据
const dashboardData = ref<DashboardResponse>({
  username: '',
  role: '',
  lastLoginTime: new Date(),
  pendingOrders: 0,
  todaySales: 0,
  topProduct: {
    id: 0,
    name: '',
    sales: 0
  }
})

// 销售趋势数据
const salesTrend = ref<SalesTrendResponse>({
  months: [],
  values: []
})

// 分类销售数据
const categorySales = ref<CategorySalesResponse>({
  years: [],
  values: {}
})

// 分类销售占比
const categoryPercentage = ref<CategoryPercentageResponse>({
  categories: [],
  percentages: []
})

// 图表实例
const salesTrendChart = ref<echarts.ECharts | null>(null)
const categorySalesChart = ref<echarts.ECharts | null>(null)
const categoryPercentageChart = ref<echarts.ECharts | null>(null)

// 获取仪表盘数据
const fetchDashboardData = async () => {
  try {
    const response = await getDashboardData() as ApiResponse<DashboardResponse>
    console.log('仪表盘数据响应:', response)
    
    if (response && response.code === 200 && response.data) {
      dashboardData.value = {
        username: response.data.username || '',
        role: response.data.role || '',
        lastLoginTime: response.data.lastLoginTime ? new Date(response.data.lastLoginTime) : new Date(),
        pendingOrders: response.data.pendingOrders || 0,
        todaySales: response.data.todaySales || 0,
        topProduct: response.data.topProduct || {
          id: 0,
          name: '',
          sales: 0
        }
      }
    } else {
      console.error('仪表盘数据格式不正确:', response)
      ElMessage.error('获取仪表盘数据失败：数据格式不正确')
    }
  } catch (error) {
    console.error('获取仪表盘数据失败:', error)
    ElMessage.error('获取仪表盘数据失败')
  }
}

// 获取销售趋势数据
const fetchSalesTrend = async () => {
  try {
    const response = await getSalesTrend() as ApiResponse<SalesTrendResponse>
    console.log('销售趋势数据响应:', response)
    
    if (response && response.code === 200 && response.data) {
      salesTrend.value = {
        months: response.data.months || [],
        values: response.data.values || []
      }
      // 更新图表
      updateSalesTrendChart()
    } else {
      console.error('销售趋势数据格式不正确:', response)
      ElMessage.error('获取销售趋势数据失败：数据格式不正确')
    }
  } catch (error) {
    console.error('获取销售趋势数据失败:', error)
    ElMessage.error('获取销售趋势数据失败')
  }
}

// 获取分类销售数据
const fetchCategorySales = async () => {
  try {
    const response = await getCategorySales() as ApiResponse<CategorySalesResponse>
    console.log('分类销售数据响应:', response)
    
    if (response && response.code === 200 && response.data) {
      categorySales.value = {
        years: response.data.years || [],
        values: response.data.values || {}
      }
      // 更新图表
      updateCategorySalesChart()
    } else {
      console.error('分类销售数据格式不正确:', response)
      ElMessage.error('获取分类销售数据失败：数据格式不正确')
    }
  } catch (error) {
    console.error('获取分类销售数据失败:', error)
    ElMessage.error('获取分类销售数据失败')
  }
}

// 获取分类销售占比
const fetchCategoryPercentage = async () => {
  try {
    const response = await getSalesPercentage() as ApiResponse<CategoryPercentageResponse>
    console.log('分类销售占比响应:', response)
    
    if (response && response.code === 200 && response.data) {
      categoryPercentage.value = {
        categories: response.data.categories || [],
        percentages: response.data.percentages || []
      }
      // 更新图表
      updateCategoryPercentageChart()
    } else {
      console.error('分类销售占比数据格式不正确:', response)
      ElMessage.error('获取分类销售占比失败：数据格式不正确')
    }
  } catch (error) {
    console.error('获取分类销售占比失败:', error)
    ElMessage.error('获取分类销售占比失败')
  }
}

// 更新销售趋势图表
const updateSalesTrendChart = () => {
  if (!salesTrendChart.value) return
  
  const option = {
    title: {
      text: '销售趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: salesTrend.value.months
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: salesTrend.value.values,
      type: 'line',
      smooth: true
    }]
  }
  
  salesTrendChart.value.setOption(option)
}

// 更新分类销售图表
const updateCategorySalesChart = () => {
  if (!categorySalesChart.value) return
  
  const series = Object.entries(categorySales.value.values).map(([category, values]) => ({
    name: category,
    type: 'bar',
    data: values
  }))
  
  const option = {
    title: {
      text: '分类销售统计'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: Object.keys(categorySales.value.values)
    },
    xAxis: {
      type: 'category',
      data: categorySales.value.years
    },
    yAxis: {
      type: 'value'
    },
    series
  }
  
  categorySalesChart.value.setOption(option)
}

// 更新分类销售占比图表
const updateCategoryPercentageChart = () => {
  if (!categoryPercentageChart.value) return
  
  const option = {
    title: {
      text: '分类销售占比'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}%'
    },
    series: [{
      type: 'pie',
      radius: '50%',
      data: categoryPercentage.value.categories.map((category, index) => ({
        name: category,
        value: categoryPercentage.value.percentages[index]
      }))
    }]
  }
  
  categoryPercentageChart.value.setOption(option)
}

// 初始化图表
const initCharts = () => {
  salesTrendChart.value = echarts.init(document.getElementById('salesTrendChart'))
  categorySalesChart.value = echarts.init(document.getElementById('categorySalesChart'))
  categoryPercentageChart.value = echarts.init(document.getElementById('categoryPercentageChart'))
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    salesTrendChart.value?.resize()
    categorySalesChart.value?.resize()
    categoryPercentageChart.value?.resize()
  })
}

onMounted(() => {
  initCharts()
  fetchDashboardData()
  fetchSalesTrend()
  fetchCategorySales()
  fetchCategoryPercentage()
})

onUnmounted(() => {
  window.removeEventListener('resize', () => {
    salesTrendChart.value?.resize()
    categorySalesChart.value?.resize()
    categoryPercentageChart.value?.resize()
  })
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.user-info-card {
  margin-bottom: 20px;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.overview-card {
  .card-content {
    text-align: center;
    padding: 20px 0;
    
    h2 {
      font-size: 24px;
      margin: 0;
      color: #409EFF;
    }
    
    h3 {
      font-size: 18px;
      margin: 0 0 10px;
    }
    
    p {
      margin: 0;
      color: #666;
    }
  }
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.chart-card {
  .chart {
    height: 400px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  p {
    margin: 10px 0;
    
    strong {
      margin-right: 10px;
      color: #666;
    }
  }
}
</style> 